
//
//  WBStausPicView.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/24.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit

class WBStausPicView: UIView {

    var viewModel: WBStatusViewModel?{
        didSet {
            calcViewSize()
            //设置urls
            urls = viewModel?.picURLs
        }
    }

    private func calcViewSize(){

        let viewSize = viewModel?.picViewSize ?? CGSize()
        //处理宽度
        //1> 单图，根据配图视图的大小，修改subviews[0]的宽高
        if viewModel?.picURLs?.count == 1 {
            // 获取第0个图像视图
            let v = subviews[0]
            //只有一张图时，宽度是整个配图视图宽度
            v.frame = CGRect(x: 0, y: WBStatusPicViewOutterMargin, width: viewSize.width, height: viewSize.height - WBStatusPicViewOutterMargin)
        }else{
            //2> 多图(无图)，恢复subview[0]的宽高，保证九宫格布局完整
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPicViewOutterMargin, width: WBStatusPicItemWidth, height: WBStatusPicItemWidth)

        }
        //修改高度约束
        HeightCons.constant = viewModel?.picViewSize.height ?? 0

    }

    @IBOutlet weak var HeightCons: NSLayoutConstraint!

    //配图视图数组
    private var urls: [WBStatusPic]? {
        didSet{
            //1.隐藏所有imageView
            for v in subviews {
                v.isHidden = true
            }

            //2.遍历urls数组，顺序设置图像
            var index = 0
            for url in urls ?? [] {
                let iv = subviews[index] as! UIImageView

                //4张图像处理
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                //判断是否是gif图,根据扩展名
                iv.subviews[0].isHidden = !(((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() == "gif")
                
                //设置图像
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                iv.isHidden = false
                index += 1
            }
        }
    }

    override func awakeFromNib() {
        setupUI()



    }

     //MARK: 监听方法
    /// 实例化照片浏览器
    ///
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
    // 浏览照片通知

    @objc private func tapImgView(tap: UITapGestureRecognizer) {

        guard let iv = tap.view ,
        let picurls = viewModel?.picURLs else {
            return
        }
        
        var selectedIndex = iv.tag
        
        //针对四张图处理
        if picurls.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        
        
        let urls = (picurls as NSArray).value(forKey: "largePic") as! [String]
        
        //处理可见的图像视图数组
        var imageViewList = [UIImageView]()
        for iv in subviews as! [UIImageView] {
            if !iv.isHidden {
                imageViewList.append(iv)
            }
        }
        
        print(selectedIndex)
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification), object: self, userInfo:
            [WBStatusCellBrowserPhotoSelectedIndexKey: selectedIndex,
            WBStatusCellBrowserPhotoURLsKey: urls,
            WBStatusCellBrowserPhotoImageViewsKey: imageViewList])
        
    }

    //cell中所有的控件都是提前准备好，设置时根据数据是否显示，不要动态创建控件
    private func setupUI() {

        backgroundColor = superview?.backgroundColor
        //超出边界的内容不显示
        clipsToBounds = true
        let count = 3
        let rect = CGRect(x: 0, y: WBStatusPicViewOutterMargin, width: WBStatusPicItemWidth, height: WBStatusPicItemWidth)
        //循环创建9个imageView
        for i in 0..<count*count {
            let iv = UIImageView()
            iv.backgroundColor = UIColor.red
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true

            //行 -> Y
            let row = CGFloat(i / count)
            //列 -> X
            let column = CGFloat(i % count)

            let offsetX = column * (WBStatusPicItemWidth + WBStatusPicViewInnerMargin)
            let offsetY = row * (WBStatusPicItemWidth + WBStatusPicViewInnerMargin)
            iv.frame = rect.offsetBy(dx: offsetX, dy: offsetY)

            addSubview(iv)

            iv.isUserInteractionEnabled = true

            //添加手势
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImgView))
            iv.addGestureRecognizer(tap)

            //设置 imageView的tag
            iv.tag = i
            
            addGifView(iv: iv)
        }
    }
    
    //添加 gif标志
    private func addGifView(iv: UIImageView) {
        let gifImgView = UIImageView(image:UIImage(named:"timeline_image_gif"))
        iv.addSubview(gifImgView)
        
        //自动布局
        gifImgView.translatesAutoresizingMaskIntoConstraints = false
        iv.addConstraint(NSLayoutConstraint(item: gifImgView, attribute: .right, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1.0, constant: 0))
        
        iv.addConstraint(NSLayoutConstraint(item: gifImgView, attribute: .bottom, relatedBy: .equal, toItem: iv, attribute: .bottom, multiplier: 1.0, constant: 0))
    }

}
